// USERMANAGER.JS
// Handles user authentication, creation, and permissions.
// ----------------------------------------------------------------------------

Ext.define('Util.UserManager', {}); // Placeholder, ignore this.

window.UserManager =
{

    sessionId : null,
    username : null,

    checkSource : function(parameter)
    {
        var hash = location.hash.substring(2, location.hash.length);
        var params = hash.split("?");
        if (params.length == 1)
            return false;
        return params[1].substring(params[1].indexOf('=') + 1);
    },

    showMessage : function(messageText)
    {
        var message = Ext.getCmp("login-message");
        message.setText(messageText, true);
        message.setVisible(true);
    },

    login : function(username, password, callback, scope)
    {
        debugger
        var me = this;
        Ext.Ajax.request(
        {
            url : '/login',
            method : 'POST',
            params :
            {
                username : username,
                password : password
            },
            success : function(response)
            {
                debugger
                var json = Ext.decode(response.responseText);
                if (json.success === false)
                {
                    UserManager.showMessage('The username or password is incorrect');
                    return;
                }
                UserManager.sessionId = response.sessionId;
                UserManager.username = username;
                var redirectURL = UserManager.checkSource('redirectURL');
                if (redirectURL)
                {
                    console.log("Redirecting to : " + redirectURL);
                }
                Ext.callback(callback, scope,
                [
                    redirectURL,
                    response.sessionId
                ]);
            },
            failure : function(resp)
            {
                debugger
                UserManager.showMessage('The username or password is incorrect')
            }
        });

    },

    // Deletes the currently-loaded user credentials.
    logout : function(callback, scope)
    {
        var me = this;
        Functions.jsonCommand("POST", "logout", {});
    }
};
